<template>
  <el-card class="main-card">
    <div class="title">{{ this.$route.name }}</div>
    <div class="book-title-container">
      <el-input v-model="book.bookName" placeholder="请输入书籍名称">
        <template slot="prepend">书籍名称</template>
      </el-input>
      <el-button
        type="primary"
        class="save-btn"
        @click="saveBookDraft"
        v-if="book.id == null">
        保存草稿
      </el-button>
      <el-button type="danger" @click="openModel" style="margin-left: 10px"> 发布书籍 </el-button>
    </div>
    <el-input placeholder="请输入书籍作者" v-model="book.bookAuthor" style='margin-top: 1.25rem'>
      <template slot="prepend">书籍作者</template>
    </el-input>
    <el-input placeholder="请输入书籍链接" v-model="book.bookUrl" style='margin-top: 1.25rem'>
      <template slot="prepend">书籍链接</template>
    </el-input>
    <mavon-editor ref="md" v-model="book.bookProfile" style="height: calc(60vh - 100px);margin-top: 1.25rem" />
    <!-- 发布书籍对话框 -->
    <el-dialog :visible.sync="addOrEdit" width="40%" top="3vh">
      <div class="dialog-title-container" slot="title">发布书籍</div>
      <el-form label-width="80px" size="medium" :model="book">
        <!--   第一行     -->
        <el-form-item label="书籍标签">
          <el-tag
            v-for="(item, index) of book.bookTags"
            :key="index"
            style="margin: 0 1rem 0 0"
            :closable="true"
            @close="removeTag(item)">
            {{ item }}
          </el-tag>
          <el-popover placement="bottom-start" width="460" trigger="click" v-if="book.bookTags.length < 3">
            <div class="popover-title">标签</div>
            <el-autocomplete
              style="width: 100%"
              v-model="tagName"
              :fetch-suggestions="searchTags"
              placeholder="请输入标签名搜索，enter可添加自定义标签"
              :trigger-on-focus="false"
              @keyup.enter.native="saveTag"
              @select="handleSelectTag">
              <template slot-scope="{ item }">
                <div>{{ item.tagName }}</div>
              </template>
            </el-autocomplete>
            <div class="popover-container">
              <div style="margin-bottom: 1rem">添加标签</div>
              <el-tag v-for="(item, index) of tagList" :key="index" :class="tagClass(item)" @click="addTag(item)">
                {{ item.tagName }}
              </el-tag>
            </div>
            <el-button type="primary" plain slot="reference" size="small"> 添加标签 </el-button>
          </el-popover>
        </el-form-item>
      <!-- 第二行 -->
        <el-form-item label="上传封面">
          <el-upload
            class="upload-cover"
            drag
            action="/api/admin/book/images"
            multiple
            :headers="headers"
            :before-upload="beforeUpload"
            :on-success="uploadCover">
            <i class="el-icon-upload" v-if="book.bookCover === ''" />
            <div class="el-upload__text" v-if="book.bookCover === ''">将文件拖到此处，或<em>点击上传</em></div>
            <img v-else :src="book.bookCover" width="360px" height="180px"  alt='书籍封面'/>
          </el-upload>
        </el-form-item>
        <!--  第三行 -->
        <el-form-item label="是否推荐">
          <el-switch
            v-model="book.isRecommend"
            active-color="#13ce66"
            inactive-color="#F4F4F5"
            :active-value="1"
            :inactive-value="0" />
        </el-form-item>
        <!--  第四行 -->
        <el-form-item label="书籍评分">
          <el-input type="textarea" v-model="book.bookRate" placeholder="评分区间0-5" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="addOrEdit = false">取 消</el-button>
        <el-button type="danger" @click="saveOrUpdateBook"> 发 表 </el-button>
      </div>
    </el-dialog>
  </el-card>
</template>

<script>
import * as imageConversion from 'image-conversion'

export default {
  name: 'Book',
  data(){
    return{
      addOrEdit: false,
      autoSave: true,
      tagName: '',
      tagList: [],
      book:{
        id:null,
        bookName: '',
        bookCover: '',
        bookAuthor: '',
        bookTags: [],
        bookProfile: '',
        bookUrl: '',
        bookRate: 0,
        isRecommend: 0
      },
      headers: { Authorization: 'Bearer ' + sessionStorage.getItem('token') }
    }
  },
  created() {
    const path = this.$route.path
    const arr = path.split('/')
    const bookId = arr[2]
    if (bookId) {
      this.axios.get('/api/admin/books/' + bookId).then(({ data }) => {
        this.book = data.data
      })
    } else {
      const book = sessionStorage.getItem('book')
      if (book) {
        this.book = JSON.parse(book)
      }
    }
  },
  destroyed() {
    this.autoSaveBook()
  },
  methods:{
    listTags() {
      this.axios.get('/api/admin/book/tags/search').then(({ data }) => {
        this.tagList = data.data
      })
    },
    openModel() {
      if (this.book.bookName.trim() === '') {
        this.$message.error('书籍名称不能为空')
        return false
      }
      if (this.book.bookAuthor.trim() === '') {
        this.$message.error('书籍作者不能为空')
        return false
      }
      if (this.book.bookUrl.trim() === '') {
        this.$message.error('书籍链接不能为空')
        return false
      }
      if (this.book.bookProfile.trim() === '') {
        this.$message.error('书籍简介不能为空')
        return false
      }
      this.listTags()
      this.addOrEdit = true
    },
    uploadCover(response) {
      this.book.bookCover = response.data
    },
    beforeUpload(file) {
      return new Promise((resolve) => {
        if (file.size / 1024 < this.config.UPLOAD_SIZE) {
          resolve(file)
        }
        imageConversion.compressAccurately(file, this.config.UPLOAD_SIZE).then((res) => {
          resolve(res)
        })
      })
    },
    saveBookDraft() {
      if (this.book.bookName.trim() === '') {
        this.$message.error('书籍名称不能为空')
        return false
      }
      if (this.book.bookProfile.trim() === '') {
        this.$message.error('书籍简介不能为空')
        return false
      }
      this.axios.post('/api/admin/book', this.book).then(({ data }) => {
        if (data.flag) {
          if (this.book.id === null) {
            this.$store.commit('removeTab', '发布书籍')
          } else {
            this.$store.commit('removeTab', '修改书籍')
          }
          sessionStorage.removeItem('book')
          this.$router.push({ path: '/book-list' })
          this.$notify.success({
            title: '成功',
            message: '保存草稿成功'
          })
        } else {
          this.$notify.error({
            title: '失败',
            message: '保存草稿失败'
          })
        }
      })
      this.autoSave = false
    },
    saveOrUpdateBook(){
      if (this.book.bookName.trim() === '') {
        this.$message.error('书籍标题不能为空')
        return false
      }
      if (this.book.bookCover.trim() === '') {
        this.$message.error('书籍封面不能为空')
        return false
      }
      if (this.book.bookAuthor.trim() === '') {
        this.$message.error('书籍作者不能为空')
        return false
      }
      if (this.book.bookProfile.trim() === '') {
        this.$message.error('书籍简介不能为空')
        return false
      }
      if (this.book.bookTags.length === 0) {
        this.$message.error('书籍标签不能为空')
        return false
      }
      if (this.book.bookUrl.trim() === '') {
        this.$message.error('书籍地址链接不能为空')
        return false
      }
      if(this.book.bookRate < 0 || this.book.bookRate > 5){
        this.$message.error('书籍评分大小非法')
        return false
      }
      this.axios
        .post('/api/admin/book',this.book).then(({ data }) => {
        if (data.flag) {
          if (this.book.id === null) {
            this.$store.commit('removeTab', '发布书籍')
          } else {
            this.$store.commit('removeTab', '修改书籍')
          }
          sessionStorage.removeItem('book')
          this.$router.push({ path: '/book-list' })
          this.$notify.success({
            title: '成功',
            message: data.message
          })
        } else {
          this.$notify.error({
            title: '失败',
            message: data.message
          })
        }
        this.addOrEdit = false
      })
    },
    addTag(item) {
      if (this.book.bookTags.indexOf(item.tagName) === -1) {
        this.book.bookTags.push(item.tagName)
      }
    },
    removeTag(item) {
      const index = this.book.bookTags.indexOf(item)
      this.book.bookTags.splice(index, 1)
    },
    searchTags(keywords, cb) {
      this.axios
        .get('/api/admin/book/tags/search', {
          params: {
            keywords: keywords
          }
        })
        .then(({ data }) => {
          cb(data.data)
        })
    },
    handleSelectTag(item) {
      this.addTag({
        tagName: item.tagName
      })
    },
    saveTag() {
      if (this.tagName.trim() !== '') {
        this.addTag({
          tagName: this.tagName
        })
        this.tagName = ''
      }
    },
    autoSaveBook() {
      if (
        this.autoSave &&
        this.book.bookName.trim() !== '' &&
        this.book.bookAuthor.trim() !== '' &&
        this.book.bookUrl.trim() !== '' &&
        this.book.bookProfile.trim() !== '' &&
        this.book.id != null
      ) {
        this.axios.post('/api/admin/book', this.book).then(({ data }) => {
          if (data.flag) {
            this.$notify.success({
              title: '成功',
              message: '自动保存成功'
            })
          } else {
            this.$notify.error({
              title: '失败',
              message: '自动保存失败'
            })
          }
        })
      }
      if (this.autoSave && this.book.id == null) {
        sessionStorage.setItem('book', JSON.stringify(this.book))
      }
    }
  },
  computed:{
    tagClass() {
      return function (item) {
        const index = this.book.bookTags.indexOf(item.tagName)
        return index !== -1 ? 'tag-item-select' : 'tag-item'
      }
    }
  },
}
</script>

<style scoped>
.book-title-container {
    display: flex;
    align-items: center;
    margin-top: 2.25rem;
}
.save-btn {
    margin-left: 0.75rem;
    background: #fff;
    color: #409EFF;
}
.popover-title {
    margin-bottom: 1rem;
    text-align: center;
}
.popover-container {
    margin-top: 1rem;
    height: 260px;
    overflow-y: auto;
}
.tag-item {
    margin-right: 1rem;
    margin-bottom: 1rem;
    cursor: pointer;
}
.tag-item-select {
    margin-right: 1rem;
    margin-bottom: 1rem;
    cursor: not-allowed;
    color: #ccccd8 !important;
}
</style>
